from django.db import models
from django.utils.translation import ugettext_lazy as _
from djwheel.utils import trunc_text
from django.contrib.syndication.feeds import Feed
from datetime import datetime
from django.core.urlresolvers import reverse

class NewsGroup(models.Model):
    name =  models.CharField(_('name'), max_length=20,
        help_text=_('part of rss url'))
    description =  models.CharField(_('description'), max_length=255)

    def __unicode__(self):
        #return '%s [%s] - %s ' % (self.name, self.lang, self.description)
        return '%s - %s ' % (self.name, self.description)

    def get_feed(self, max_news=10):
        class NewsFeed(Feed):
            title = self.description
            #link = property(lambda self: reverse(self.name))
            link = self.get_absolute_url()
            description = self.description
            title_template = 'news_title.html'
            description_template = 'news_description.html'

            def items(self_):
                return News.objects.filter(group=self)[:max_news]

            def item_pubdate(self, item):
                return datetime(*item.date.timetuple()[0:3])
        return NewsFeed

    def get_absolute_url(self):
        return reverse('news', args=[self.name])

    class Meta:
        ordering = ('name',)
        verbose_name = _('news group')
        verbose_name_plural = _('news groups')

def default_group():
    news = News.objects.all()
    if news.count() > 0:
        return news[0].group
    else:
        groups = NewsGroup.objects.all()
        if groups.count() > 0:
            return groups[0]
        else:
            return 0

class News(models.Model):
    group = models.ForeignKey(NewsGroup, verbose_name=_('group'), default=default_group)
    #group = models.ForeignKey(NewsGroup, verbose_name=_('group'), default=2)
    date = models.DateField(_('date'))
    title = models.CharField(_('title'), max_length=2048)
    text = models.TextField(_('text'))
    full_text = models.TextField(_('full text'), blank=True,
        help_text=_('full text (for large texts)'))
    always_on_top = models.BooleanField(_('always on top'), default=False)

    def adm_text(self):
        return trunc_text(self.text, 255, ' [...]', by_spaces=True)
    adm_text.short_description = _('text')
    #adm_text.allow_tags = True

    def get_full_text(self):
        return self.full_text and self.full_text or self.text

    def get_absolute_url(self):
        return reverse('news_item', args=[self.group.name, self.id] )

    class Meta:
        ordering = ('-date',)
        get_latest_by = 'date'
        verbose_name = _('news item')
        verbose_name_plural = _('news items')

    def __unicode__(self):
        return self.title
